package com.example.studyes.init;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: hanll
 * @ClassName: ElasticSearchInit
 * @Date: 2022-12-15 17:51
 * @Version: 1.0
 * @Description:项目启动初始化索引
 */
@Component
public class ElasticSearchInitializing implements InitializingBean {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void afterPropertiesSet() throws Exception {
        initElasticSearch();
    }

    public void initElasticSearch() {
        try {
            //创建索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest("test");
            CreateIndexResponse response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            boolean acknowledged = response.isAcknowledged();
            System.out.println("创建索引"+acknowledged);
            restHighLevelClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
